package com.pie4cloud.pie.bus.service.impl;


import com.pie4cloud.pie.bus.service.KafkaTopicService;
import com.pie4cloud.pie.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.ListTopicsResult;
import org.apache.kafka.common.KafkaFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;

@Slf4j
@Service
public class KafkaTopicServiceImpl implements KafkaTopicService {
	private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
	private AdminClient adminClient;


	public R<List<Map<String,String>>> getTopicList(){
		ListTopicsResult result =adminClient.listTopics();
		KafkaFuture<Set<String>> names = result.names();
		List<Map<String,String>> list=new ArrayList<>();
		try {
			names.get().forEach((k)->{
				Map<String,String> map=new HashMap<>();
				map.put("topicName",k);
				list.add(map);
			});
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		return R.ok(list);
	}

	public R delTopic(String topicName){
	/*	DeleteTopicsResult result  = adminClient.deleteTopics(Collections.singleton(topicName));
		result.all().get();*/
		try {
			adminClient.deleteTopics(Collections.singleton(topicName)).all().get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return R.ok();
	}

}
